const express = require('express');
const uuid = require('node-uuid');
const { Message,MessageList } = require('../utils/message');
const orderModel = require('../models/order');
const stockModel = require('../models/stock');

const router = express.Router();

router.post('/',(req,res,next)=>{
  const {customer,cost,serviceList,agreeTime}=req.body;
  const id = uuid.v1();
  const status='预约中';
  const startTime=Date.now();
  const endTime='';
  const beautyProgress=0;
  const order = new orderModel({id,agreeTime,startTime,endTime,customer,status,beautyProgress,cost,serviceList});
  order.save().then(data=>{
    if(data){
      res.json(Message(200,'申请成功'))
    }
  })
});

router.delete('/',(req,res,next)=>{
  const {id}=req.query;
  if(id){
    orderModel.deleteOne({id}).then(data=>{
      if(data.deletedCount!==0){
        res.json(Message(200,'删除成功！'))
      }else{
        res.json(Message(400,'删除失败'))
      }
    })
  }else{
    res.json(Message(400,'缺少参数id'))
  }
})

router.put('/',(req,res,next)=>{
  const {id}=req.query;
  const {status,materialIdList,beautyProgress}=req.body;
  const modifyObj={};
  modifyObj.status=status;
  modifyObj.beautyProgress=beautyProgress;
  if(status==='已结束'||status==='美容已完成') modifyObj.beautyProgress=100;
  if(status==='已结束') {
    modifyObj.endTime=Date.now();
    if(materialIdList){
      materialIdList.forEach(element => {
        stockModel.findOne({id:element.materialId}).then(data=>{
          if(data){
            const newNum=data.number-Number(element.expendNum);
            stockModel.updateOne({id:element.materialId},{number:newNum}).then(data=>{
              if(data.acknowledged&&data.modifiedCount!==0){
                console.log('success')
              }else{
                console.log('error')
              }
            })
          }
        })
      });
    }
  }
  if(id){
    orderModel.updateOne({id},modifyObj).then(data=>{
      if(data.acknowledged&&data.modifiedCount!==0){
        res.json(Message(200,'修改成功！'));
      }else{
        res.json(Message(400,'修改失败！'));
      }
    })
  }else{
    res.json(Message(400,'缺少参数id'))
  }
})

router.get('/',(req,res,next)=>{
  const {id,customer,status,startTime,endTime}=req.query;
  const {page,pageSize}=req.query;
  const queryObj={};
  if(startTime&&endTime){
    const time1=new Date(startTime);
    const time2=new Date(endTime);
    queryObj.$and=[{endTime: {$gt: time1}},{endTime: {$lt: time2}}]
  }
  if(id) queryObj.id=id;
  if(customer) queryObj.customer=customer;
  if(status) queryObj.status=status;
  if(page&&pageSize){
    orderModel.find(queryObj).count((err,total)=>{
      orderModel.find(queryObj).limit(pageSize).skip((page-1)*pageSize).then(data=>{
          res.json(MessageList(200,'',data,page,pageSize,total))
        })
    })
    return
  }
  orderModel.find(queryObj).count((err,count)=>{
    orderModel.find(queryObj).then(data=>{
      if(!id){
        res.json(MessageList(200,'',data,0,0,count));
      }else{
        res.json(Message(200,'',data));
      }
    })
  })
})

router.get('/echartsData',(req,res,next)=>{
  let {year}=req.query;
  year=Number(year)
  const sy=new Date(year.toString());
  const ey=new Date((year+1).toString());
  const queryObj={};
  queryObj.$and=[{endTime: {'$gte': sy}},{endTime: {'$lt': ey}}]
  const arr=[];
  for(let i=0;i<12;i++){
    arr[i]=0;
  }
  orderModel.find(queryObj).count((err,count)=>{
    orderModel.find(queryObj).then(data=>{
        data.forEach((item,index)=>{
          arr[new Date(item.endTime).getMonth()]+=item.cost
        })
        res.json(MessageList(200,'',arr,0,0,0))
    })
  })
})

module.exports=router;